import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isEmpty from "lodash/isEmpty";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _class, _class2;

/**
 * AuthorityCopy - 租户级权限维护tab页 - 权限复制
 * @date: 2018-7-31

 */
import React from 'react';
import { connect } from 'dva';
import { Form, Input, message, Modal, Popconfirm, Table } from 'antd';
import { Bind } from 'lodash-decorators';
import uuidv4 from 'uuid/v4';
import Lov from 'components/Lov';
import { Button as ButtonPermission } from 'components/Permission';
import intl from 'utils/intl';
import notification from 'utils/notification';
import { tableScrollWidth } from 'utils/utils';
import { queryLov } from 'services/api';
import { operatorRender } from 'utils/renderer';
import AddDataLov from "./AddDataLov";
/**
 * 使用 Form.Item 组件
 */

var FormItem = Form.Item;
/**
 * 租户级权限管理 - 权限复制
 * @extends {Component} - React.Component
 * @reactProps {Object} authorityManagement - 数据源
 * @reactProps {Object} loading - 数据加载是否完成
 * @reactProps {Object} form - 表单对象
 * @reactProps {Function} [dispatch=function(e) {return e;}] - redux dispatch方法
 * @return React.element
 */

var AuthorityCopy = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = connect(function (_ref) {
  var authorityManagement = _ref.authorityManagement,
      loading = _ref.loading;
  return {
    authorityManagement: authorityManagement,
    loading: loading.models.authorityManagement
  };
}), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec(_class = _dec2(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(AuthorityCopy, _React$Component);

  var _super = _createSuper(AuthorityCopy);

  /**
   *Creates an instance of AuthorityCopy.
   * @param {Object} props 属性
   */
  function AuthorityCopy(props) {
    var _this;

    _classCallCheck(this, AuthorityCopy);

    _this = _super.call(this, props);
    _this.PageSize = 10;
    _this.dataSourceRef = React.createRef();
    _this.state = {
      newCreateRows: [],
      addModalVisible: false
    };
    return _this;
  }
  /**
   *增加一行
   */


  _createClass(AuthorityCopy, [{
    key: "addData",
    value: function addData(record) {
      var arr = record.map(function (item) {
        var authorityLineId = "authorityLineId".concat(uuidv4());
        var data = {
          authorityLineId: authorityLineId,
          isCreate: true,
          isEditing: true
        };
        return _objectSpread(_objectSpread({}, data), item);
      });
      this.setState({
        newCreateRows: [].concat(_toConsumableArray(this.state.newCreateRows), _toConsumableArray(arr)),
        addModalVisible: false
      });
    }
    /**
     *行取消事件
     *
     * @param {Object} record 行数据
     */

  }, {
    key: "cancel",
    value: function cancel(record) {
      var dispatch = this.props.dispatch;
      var newCreateRows = this.state.newCreateRows;

      if (record.isCreate) {
        var listData = newCreateRows.filter(function (item) {
          return item.authorityLineId !== record.authorityLineId;
        });
        this.setState({
          newCreateRows: listData
        });
        dispatch({
          type: 'authorityManagement/removeNewAdd',
          payload: {}
        });
      } else {
        this.edit(record, false);
      }
    }
    /**
     *编辑事件
     *
     * @param {Object} record 行数据
     * @param {Boolean} flag 是否编辑状态标记
     */

  }, {
    key: "edit",
    value: function edit() {
      var record = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var flag = arguments.length > 1 ? arguments[1] : undefined;
      var _this$props = this.props,
          dispatch = _this$props.dispatch,
          _this$props$authority = _this$props.authorityManagement.data,
          data = _this$props$authority === void 0 ? {} : _this$props$authority;
      var index = data.list.findIndex(function (item) {
        return item.authorityLineId === record.authorityLineId;
      });
      dispatch({
        type: 'authorityManagement/editRow',
        payload: {
          data: [].concat(_toConsumableArray(data.slice(0, index)), [_objectSpread(_objectSpread({}, record), {}, {
            isEditing: flag
          })], _toConsumableArray(data.slice(index + 1)))
        }
      });
    }
    /**
     *保存数据
     */

  }, {
    key: "dataSave",
    value: function dataSave() {
      var _this2 = this;

      var _this$props2 = this.props,
          form = _this$props2.form,
          dispatch = _this$props2.dispatch,
          userId = _this$props2.userId,
          refresh = _this$props2.refresh,
          authorityCopy = _this$props2.authorityCopy;
      var newCreateRows = this.state.newCreateRows;
      form.validateFields(function (err, values) {
        if (!err) {
          var arr = [];
          var isNewRowKeys = newCreateRows.filter(function (v) {
            return v.isEditing;
          });
          isNewRowKeys.forEach(function (item) {
            arr.push(values["".concat(item.authorityLineId, "#dataId")]);
          });
          dispatch({
            type: 'authorityManagement/copyAuthority',
            payload: {
              userId: userId,
              copyUserIdList: arr
            }
          }).then(function (response) {
            if (response) {
              notification.success();

              if (authorityCopy) {
                _this2.setState({
                  newCreateRows: []
                });

                authorityCopy();
              }

              refresh();
            }
          });
        }
      });
    }
    /**
     *lov选中后渲染同行其他数据
     *
     * @param {Object} lovRecord
     * @param {Object} tableRecord
     */

  }, {
    key: "setDataCode",
    value: function setDataCode() {
      var lovRecord = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var tableRecord = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      this.props.form.setFieldsValue(_defineProperty({}, "".concat(tableRecord.authorityLineId, "#dataCode"), lovRecord.realName));
    }
    /**
     * 展示弹出框
     */

  }, {
    key: "onShowAddModal",
    value: function onShowAddModal() {
      var _this3 = this;

      queryLov({
        viewCode: 'CIAM.USER_AUTHORITY_USER'
      }).then(function (res) {
        var lovInfo = _objectSpread({}, res);

        if (!_isEmpty(lovInfo)) {
          var hasCode = lovInfo.viewCode;

          if (hasCode) {
            _this3.setState({
              lov: lovInfo
            });
          } else {
            message.error(intl.get('cpaas.common.components.lov.notification.undefined').d('值集视图未定义!'));
          }

          _this3.setState({
            addModalVisible: true
          });
        }
      });
    }
    /**
     * 隐藏弹出框
     */

  }, {
    key: "onHideAddModal",
    value: function onHideAddModal() {
      this.dataSourceRef.current.state.addRows = [];
      this.setState({
        addModalVisible: false
      });
    }
    /**
     *渲染事件
     *
     * @returns
     */

  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var _this$props3 = this.props,
          loading = _this$props3.loading,
          organizationId = _this$props3.organizationId,
          userId = _this$props3.userId,
          path = _this$props3.path,
          copyModalVisible = _this$props3.copyModalVisible,
          authorityCopy = _this$props3.authorityCopy;
      var _this$state = this.state,
          _this$state$newCreate = _this$state.newCreateRows,
          newCreateRows = _this$state$newCreate === void 0 ? [] : _this$state$newCreate,
          addModalVisible = _this$state.addModalVisible,
          lov = _this$state.lov;
      var getFieldDecorator = this.props.form.getFieldDecorator;
      var columns = [{
        title: intl.get('ciam.authority.model.authorityManagement.dataName').d('账号'),
        dataIndex: 'dataId',
        width: 200,
        render: function render(text, tableRecord) {
          return tableRecord.isEditing ? /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(tableRecord.authorityLineId, "#dataId"), {
            initialValue: tableRecord.dataId,
            rules: [{
              required: true,
              message: intl.get('cpaas.common.validation.notNull', {
                name: intl.get('ciam.authority.model.authorityManagement.dataName').d('账号')
              })
            }]
          })( /*#__PURE__*/React.createElement(Lov, {
            code: "CIAM.USER_AUTHORITY_USER",
            queryParams: {
              organizationId: organizationId,
              userId: userId
            },
            textValue: tableRecord.dataName,
            onChange: function onChange(_, record) {
              return _this4.setDataCode(record, tableRecord);
            }
          }))) : /*#__PURE__*/React.createElement("div", null, text);
        }
      }, {
        title: intl.get('ciam.authority.model.authorityManagement.dataCode').d('名称'),
        dataIndex: 'dataCode',
        render: function render(text, record) {
          return record.isEditing ? /*#__PURE__*/React.createElement(FormItem, null, getFieldDecorator("".concat(record.authorityLineId, "#dataCode"), {
            initialValue: record.dataCode
          })( /*#__PURE__*/React.createElement(Input, {
            disabled: true
          }))) : /*#__PURE__*/React.createElement("div", null, text);
        }
      }, {
        title: intl.get('cpaas.common.button.action').d('操作'),
        width: 85,
        render: function render(_, record) {
          var operators = [{
            key: 'cancel',
            ele: /*#__PURE__*/React.createElement(Popconfirm, {
              title: intl.get('ciam.authority.view.message.confirmDelete').d('确认取消？'),
              onConfirm: function onConfirm() {
                return _this4.cancel(record);
              }
            }, /*#__PURE__*/React.createElement(ButtonPermission, {
              type: "text",
              permissionList: [{
                code: "".concat(path, ".button.cancelAuthority"),
                type: 'button',
                meaning: '权限维护-取消权限复制'
              }]
            }, intl.get('cpaas.common.button.cancel').d('取消'))),
            len: 2,
            title: intl.get('cpaas.common.button.cancel').d('取消')
          }];
          return operatorRender(operators);
        }
      }];
      var addModalOptions = {
        rowKey: 'userId',
        lov: lov,
        queryParams: {
          userId: userId,
          organizationId: organizationId
        },
        modalVisible: addModalVisible,
        onHideAddModal: this.onHideAddModal,
        addData: this.addData,
        ref: this.dataSourceRef
      };
      return /*#__PURE__*/React.createElement(Modal, {
        title: intl.get('ciam.authority.view.button.copy').d('权限复制'),
        visible: copyModalVisible,
        onCancel: function onCancel() {
          _this4.setState({
            newCreateRows: []
          });

          authorityCopy(false);
        },
        width: 600,
        footer: null
      }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(path, ".button.createAuthority"),
          type: 'button',
          meaning: '权限维护-新建权限复制'
        }],
        icon: "plus",
        style: {
          margin: '0 10px 10px 0'
        },
        onClick: function onClick() {
          return _this4.onShowAddModal();
        }
      }, intl.get('cpaas.common.button.create').d('新建')), /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(path, ".button.saveAuthority"),
          type: 'button',
          meaning: '权限维护-保存权限复制'
        }],
        icon: "save",
        type: "primary",
        onClick: function onClick() {
          return _this4.dataSave();
        }
      }, intl.get('cpaas.common.button.save').d('保存'))), /*#__PURE__*/React.createElement("div", null, intl.get('ciam.authority.view.message.title.authorityCopy').d('权限复制操作会将当前用户的权限一键添加至其他用户，请谨慎操作！')), /*#__PURE__*/React.createElement(Table, {
        bordered: true,
        rowKey: "authorityLineId",
        pagination: false,
        loading: loading,
        dataSource: newCreateRows,
        columns: columns,
        scroll: {
          x: tableScrollWidth(columns)
        }
      })), /*#__PURE__*/React.createElement(AddDataLov, addModalOptions));
    }
  }]);

  return AuthorityCopy;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "addData", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "addData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "cancel", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "cancel"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "edit", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "edit"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "dataSave", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "dataSave"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "setDataCode", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "setDataCode"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onShowAddModal", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "onShowAddModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onHideAddModal", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "onHideAddModal"), _class2.prototype)), _class2)) || _class) || _class);
export { AuthorityCopy as default };